<script setup>
import { onMounted, ref } from 'vue'
import counter from './components/counter.vue'
import {
  memberCart,
  memberCartSelected,
  memberCartId,
  memberCartCount,
  memberCartDel
} from '@/api/cart'
import { ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import GoodsCarousel from './components/GoodsCarousel.vue'
import { getRecommands } from '@/api/detail'
import goDetail from '@/utils/goDetail'
import router from '@/router'
import { useUserStore } from '@/stores'
const store = useUserStore()
onMounted(() => {
  if (!store.isLogined) {
    router.push('/login')
    ElMessage.error('请先登录！')
  }
})

// 猜你喜欢
const likeList = ref([])
const getList = async () => {
  const res = await getRecommands()
  likeList.value = res.data.result
}
getList()

const tableData = ref([])
const multipleTableRef = ref()
const allSelect = ref(false)
const canSelect = ref(false)
//获取数据
const getData = async () => {
  const res = await memberCart()
  tableData.value = res.data.result
  if (tableData.value.length > 0) {
    allSelect.value = true
    res.data.result.forEach(item => {
      if (item.selected === false) {
        allSelect.value = false
        return
      }
    })
  }
  getTotalGoodsCount()
  getCheckCount()
  getTotalMoney()
}
getData()
//全选
const allSelectEvent = async () => {
  if (allSelect.value) {
    canSelect.value = true
    await memberCartSelected({ selected: false })
    await getData()
    canSelect.value = false
  } else {
    canSelect.value = true
    await memberCartSelected({ selected: true })
    await getData()
    canSelect.value = false
  }
}
//修改购物车内容
const changeItem = async (id, selected, count) => {
  canSelect.value = true
  await memberCartId(id, { selected, count })
  await getData()
  canSelect.value = false
}
//购物车总数
const totalCount = ref(0)
const getTotalGoodsCount = async () => {
  const res = await memberCartCount()
  totalCount.value = res.data.result.count
}
//确认购物车总数
const checkCount = ref(0)
const getCheckCount = () => {
  checkCount.value = 0
  tableData.value.forEach(item => {
    if (item.selected) checkCount.value += item.count
  })
}
//总金额
const totalMoney = ref(0)
const getTotalMoney = () => {
  totalMoney.value = 0
  tableData.value.forEach(item => {
    if (item.selected) totalMoney.value += item.count * item.price
  })
}
//删除

const delEvent = async id => {
  await memberCartDel({ ids: id })
  await getData()
  ElMessage.success('删除成功！')
}
//删除选择商品
const delSelectEvent = async () => {
  let ids = []
  tableData.value.forEach(item => {
    if (item.selected) ids.push(item.skuId)
  })
  delEvent(ids)
  await getData()
  ElMessage.success('删除成功！')
}
//清空失效商品
const clearInvalid = async () => {
  memberCartDel({ ids: [], clearInvalid: true })
  await getData()
  ElMessage.success('清空成功！')
}
const goCheckout = () => {
  if (checkCount.value > 0) router.push('/checkout')
  else ElMessage.error('请选择商品')
}
</script>
<template>
  <div class="shopping-cart">
    <div class="breadcrumb">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main">
      <el-table class="custom-table" ref="multipleTableRef" :data="tableData" style="width: 100%">
        <el-table-column width="110">
          <template #header>
            <el-checkbox v-model="allSelect" @click="allSelectEvent" :disabled="canSelect"
              >全选</el-checkbox
            >
          </template>
          <template #default="row">
            <el-checkbox
              v-model="row.row.selected"
              :disabled="canSelect"
              @click="changeItem(row.row.skuId, !row.row.selected, row.row.count)"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" align="center">
          <template #default="row">
            <div class="goodDet">
              <img :src="row.row.picture" alt="" class="goodImg" @click="goDetail(row.row.id)" />
              <div class="content">
                <div class="top">{{ row.row.name }}</div>
                <div class="but">
                  <div class="con">
                    <div class="con-text">{{ row.row.attrsText }}</div>
                    <el-icon class="icon"><ArrowDown /></el-icon>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单价" width="220">
          <template #default="row">
            <span>￥{{ row.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" property="address" width="180" label="数量">
          <template #default="row">
            <counter
              style="margin: 0 auto"
              :modelValue="row.row.count"
              @update:modelValue="val => changeItem(row.row.skuId, row.row.selected, val)"
            ></counter>
          </template>
        </el-table-column>
        <el-table-column align="center" property="address" width="180" label="小计">
          <template #default="row">
            <span class="totalMoney">￥{{ row.row.count * row.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" property="address" width="140" label="操作">
          <template #default="row" class="opera">
            <div>移入收藏夹</div>

            <el-popconfirm
              title="你确认删除嘛？"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="delEvent([row.row.skuId])"
            >
              <template #reference>
                <div style="color: #27baa8">删除</div>
              </template>
            </el-popconfirm>

            <div>找相似</div>
          </template>
        </el-table-column>
        <template #empty>
          <div class="custom-empty">
            <img src="@/assets/icons/cart/下载.png" alt="No data" />
            <p>购物车内暂时没有商品</p>
            <el-button type="success" style="width: 180px; height: 50px">继续逛逛</el-button>
          </div>
        </template>
      </el-table>
    </div>
    <div class="bottom">
      <div class="lef">
        <el-checkbox
          v-model="allSelect"
          @click="allSelectEvent"
          :disabled="canSelect"
          style="margin-right: 20px"
        >
          全选
        </el-checkbox>
        <el-popconfirm
          title="你确认删除嘛？"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="delSelectEvent"
        >
          <template #reference>
            <span>删除商品</span>
          </template>
        </el-popconfirm>

        <span>移入收藏夹</span>

        <el-popconfirm
          title="你确认清空失效商品嘛？"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="clearInvalid"
        >
          <template #reference>
            <span>清空失效商品</span>
          </template>
        </el-popconfirm>
      </div>
      <div class="right">
        共计{{ totalCount }}件商品，已选择{{ checkCount }}件，商品合计：<span
          >￥{{ totalMoney }}</span
        >
        <el-button type="primary" style="width: 180px; height: 50px" @click="goCheckout"
          >下单结算</el-button
        >
      </div>
    </div>
    <GoodsCarousel :products="likeList" style="margin-bottom: 30px" />
  </div>
</template>
<style scoped lang="scss">
.shopping-cart {
  width: 100%;
  margin: 0 auto;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  .breadcrumb {
    width: 1220px;
    margin: 30px 0px;
  }
  .main {
    width: 1240px;
    background-color: #fff;
    text-align: center;
    .custom-table :deep(.el-table__cell) {
      padding: 10px 23px;
    }
    .custom-table :deep(.el-table__header) {
      height: 75px; /* 调整表头高度 */
    }
    .totalMoney {
      color: #cf4444;
    }
    .goodDet {
      display: flex;
      .goodImg {
        height: 100px;
        width: 100px;
        padding-right: 10px;
        cursor: pointer;
      }
      .content {
        padding-top: 15px;
        font-size: 15px;
        flex: 1;
        line-height: 30px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        .but {
          color: #999999;
          text-align: left;
          .con {
            position: relative;
            height: 25px;
            padding: 5px 8px;
            border: #dfdfdf solid 1px;
            width: 228px;
            display: flex;
            white-space: nowrap;
            align-items: center;
            .con-text {
              width: 190px;
              font-size: 13px;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            .icon {
              position: absolute;
              top: 0;
              right: 0;
              height: 25px;
              width: 25px;
              border-left: #dfdfdf solid 1px;
            }
          }
        }
        .top {
          height: 30px;
          overflow: hidden;
          text-overflow: ellipsis;
          padding-bottom: 10px;
          text-align: left;
        }
      }
    }
    .custom-empty {
      box-sizing: border-box;
      padding: 110px 0;
      height: 550px;
      text-align: center;
    }
  }
  .bottom {
    background-color: #fff;
    width: 1240px;
    margin: 20px 0px;
    padding: 15px 35px;

    height: 80px;
    display: flex;
    box-sizing: border-box;

    line-height: 50px;
    .lef {
      flex: 1;
      text-align: left;
      span {
        margin-left: 15px;
        cursor: pointer;
      }
    }
    .right {
      flex: 1;
      text-align: right;
      span {
        margin-right: 20px;
        font-size: 18px;
        font-weight: bold;
        color: #cf4444;
      }
    }
  }
}
</style>
